import os
from app import create_app
import subprocess
import time
import socket

def is_port_in_use(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('localhost', port)) == 0
    

def launch_chrome():
    if is_port_in_use(9222):
        print("端口 9222 已被占用，请释放该端口。")
        return
    chrome_path = "C:/Program Files/Google/Chrome/Application/chrome.exe"
    url = "http://127.0.0.1:5000"
    args = [
                chrome_path,
                "--remote-debugging-port=9222",
                "--user-data-dir=C:\\chromedevprofile",  # 注意双反斜杠
                url
            ]
    try:
        subprocess.Popen(args)
        time.sleep(5)  
    except Exception as e:
        print("启动 Chrome 浏览器时出现错误:", e)

app = create_app()

if __name__ == '__main__':
    if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
        launch_chrome()
    app.run(debug=True)